package com.gx.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Iterables;
import com.gx.base.CurrentUser;
import com.gx.constant.ShiroConstants;
import com.gx.core.shiro.utils.ShiroUtils;
import com.gx.domain.SysRoleUserExample;
import com.gx.domain.SysUser;
import com.gx.domain.SysUserExample;
import com.gx.id.DefaultIdGenerator;
import com.gx.id.IdGenerator;
import com.gx.mapper.SysRoleUserMapper;
import com.gx.mapper.SysUserMapper;
import com.gx.service.api.SysMenuService;
import com.gx.service.api.SysUserService;
import com.gx.utils.StringUtils;
import com.gx.utils.bean.BeanUtilsEx;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

//@CacheConfig(cacheNames = "GoodsType")
@Service
public class SysUserServiceImpl implements SysUserService {

    private IdGenerator idGenerator = DefaultIdGenerator.getInstance();

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;


    @Cacheable(key = "#test1", value = "skus1")
    @Override
    public String CacheMethodTest1(String test1) {
        System.out.println("数据库查询代码");
        return "查询到的结果集";
    }


//    public String ssss() {
//        CacheManager cacheManager = new CacheManager("classpath:ehcache.xml");
//        CacheConfiguration cacheConfig = new CacheConfiguration();
//        cacheConfig.name("").maxBytesLocalHeap(100, MemoryUnit.MEGABYTES);
//        Searchable searchable = new Searchable();
//        //指定Cache的Searchable对象。
//        cacheConfig.searchable(searchable);
//        //如下指定也行
////    cacheConfig.addSearchable(searchable);
//        Cache cache1 = new Cache(cacheConfig);
//        cacheManager.addCache(cache1);
//
//        return "";
//    }
//
//
//    public String select(String id) {
//
//
//        System.out.println("select()执行了=============");
//        return "模拟数据库查询";
//    }

    //    @Cacheable(value = "user", key = "#username")
    @Override
    public SysUser queryByUserName(String username) {
        SysUserExample sysUserExample = new SysUserExample();
        SysUserExample.Criteria criteria = sysUserExample.createCriteria();
        criteria.andUsernameEqualTo(username);
        return Iterables.getFirst(sysUserMapper.selectByExample(sysUserExample), null);
    }

    //    @Cacheable(value = "user", key = "#userId")
    @Override
    public SysUser queryObject(String userId) {
        SysUserExample sysUserExample = new SysUserExample();
        SysUserExample.Criteria criteria = sysUserExample.createCriteria();
        criteria.andUserIdEqualTo(userId);

        return Iterables.getFirst(sysUserMapper.selectByExample(sysUserExample), null);
    }

    //    @CachePut(value = "user", key = "#user.id")
    @Override
    public void save(SysUser user) {
        user.setId(idGenerator.generateId());
        user.setPassword(DigestUtils.sha256Hex(user.getPassword()));
        user.setCreateDate(new Date());
        user.setStatus(new Byte("1")); // 默认启用用户
        sysUserMapper.insert(user);
    }

    //    @CachePut(value = "user", key = "#user.id")
    @Override
    public void updateByUserId(SysUser user) {
        SysUserExample sysUserExample = new SysUserExample();
        SysUserExample.Criteria criteria = sysUserExample.createCriteria();
        criteria.andUserIdEqualTo(user.getUserId());
        sysUserMapper.updateByExample(user, sysUserExample);
    }

    //    @CachePut(value = "user", key = "#sysUser.id")
    @Override
    public SysUser updateBySelective(SysUser sysUser) {
        SysUserExample sysUserExample = new SysUserExample();
        sysUser.setPassword(null); // 所有更改用户信息不能同时更改密码
        SysUserExample.Criteria criteria = sysUserExample.createCriteria();
        criteria.andIdEqualTo(sysUser.getId());
        sysUserMapper.updateByExampleSelective(sysUser, sysUserExample);
        return sysUser;
    }

    @Override
    public void deleteBatch(List<String> userIds) {
        SysUserExample sysUserExample = new SysUserExample();
        SysUserExample.Criteria criteria = sysUserExample.createCriteria();
        criteria.andUserIdIn(userIds);
        sysUserMapper.deleteByExample(sysUserExample);
    }

    @Override
    public int batchDelete(List<Long> ids) {
        // 删除用户前优先删除角色绑定（需要加事务，否则角色绑定清空，用户未删除）
        SysRoleUserExample sysRoleUserExample = new SysRoleUserExample();
        SysRoleUserExample.Criteria roleUserExampleCriteria = sysRoleUserExample.createCriteria();
        roleUserExampleCriteria.andUserIdIn(ids);
        sysRoleUserMapper.deleteByExample(sysRoleUserExample);

        // 删除用户（一般用户不删除只做无效）
        SysUserExample sysUserExample = new SysUserExample();
        SysUserExample.Criteria criteria = sysUserExample.createCriteria();
        criteria.andIdIn(ids);
        return sysUserMapper.deleteByExample(sysUserExample);
    }

    @Override
    public List<SysUser> queryAll() {
        SysUserExample sysUserExample = new SysUserExample();
        return sysUserMapper.selectByExample(sysUserExample);
    }

    @Override
    public void setMenuAndRoles(String username) {
        SysUserExample sysUserExample = new SysUserExample();
        SysUserExample.Criteria criteria = sysUserExample.createCriteria();
        criteria.andUserIdEqualTo(username);
        SysUser sysUser = sysUserMapper.selectByExample(sysUserExample).stream().findFirst().get();
        CurrentUser currentUser = new CurrentUser();
        BeanUtilsEx.copyProperties(sysUser, currentUser);
        Subject subjct = ShiroUtils.getSubjct();
        Session session = subjct.getSession();
        JSONArray menuJsonList = sysMenuService.getMenuJsonList();
        session.setAttribute("menus", menuJsonList); // 写死


    }

    @Override
    public List<String> queryAllPermissions(String userId) {
        return sysUserMapper.queryAllPermissions(userId);
    }

    @Override
    public void updateCurrentUserCache(String sysUserId) {
        CurrentUser currentUser = ShiroUtils.getCurrentUser();
        if (StringUtils.equals(currentUser.getUserId(), sysUserId)) {
            SysUser user = queryObject(sysUserId);
            CurrentUser newCurrentUser = new CurrentUser();
            BeanUtilsEx.copyProperties(newCurrentUser, user);
            ShiroUtils.setCurrentUser(newCurrentUser); // 重新授权更新权限信息
            Session session = ShiroUtils.getSession();
            session.setAttribute(ShiroConstants.CURRENT_USER, newCurrentUser); // 更新session信息
        }
    }

    @Override
    public int updatePassword(String userId, SysUser sysUser) {

        SysUserExample sysUserExample = new SysUserExample();
        SysUserExample.Criteria criteria = sysUserExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        return sysUserMapper.updateByExampleSelective(sysUser, sysUserExample);
    }
}
